package com.hadoop.component;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.hadoop.dao.redis.RedisDao;
import com.hadoop.mybatis.vo.FileAttrVo;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2017/10/13
 */
@Component
public class UploadFileBizComponent {
    @Resource
    private RedisDao redisDao;

    @Value("${base.file.read.path}")
    private String filePath;

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    /**
     * 上传文件
     * @param key
     * @param fileAttrVo
     * @return
     */
    public boolean uploadFile(String key, FileAttrVo fileAttrVo) {
        String fileName = redisDao.hget(key, fileAttrVo.getName());
        if (StringUtils.isNotBlank(fileName)) {
            return false;
        }

        Gson gson = new Gson();
        String json = gson.toJson(fileAttrVo);
        return redisDao.hset(key, fileAttrVo.getName(), json);
    }

    /**
     * 我的文件列表
     * @param key
     * @return
     */
    public List<FileAttrVo> fileAttrVoList(String key) {
        Map<String,String> param = redisDao.hgetAll(key);
        List<FileAttrVo> voList = Lists.newArrayList();
        Gson gson = new Gson();
        if (MapUtils.isNotEmpty(param)) {
            for (String val : param.values()) {
                FileAttrVo vo = gson.fromJson(val, FileAttrVo.class);
                voList.add(vo);
            }
        }
        return voList;
    }

    /**
     * 删除上传的文件
     * @param key
     * @param field
     * @return
     */
    public boolean delFile(String key, String field) {
        return redisDao.hDel(key, field);
    }
}
